import Model from "../model/Model";
import TipUi from "../../ui/tip/TipUi";
import { pomelo } from "../lib/pomelo-creator-client";

/**
 * 网络
 */
export default class Net {
    private static onPushMessageBindFunc;
    /**
     * 连接pomelo
     */
	public static connect (callback:(error:boolean)=>void) {
		pomelo.init({
            host:"192.168.99.100",
            port:3010,
            log:true
        },(err)=>{
            pomelo.request("gate.gateHandler.getEntry","hello pomelo",(data)=>{
                console.log(data);
                pomelo.disconnect(()=>{
                    pomelo.init({
                        host:data.connector.host,
                        port:data.connector.port,
                        log:true
                    },()=>{
                        this.onPushMessageBindFunc = this.onPushMessageBindFunc || this.onPushMessage.bind(this);
                        pomelo.on("push", this.onPushMessageBindFunc);
                        callback(false);
                    });
                });
            });
        });
    };
    /**
     * 断开连接
     * @param cb 回调
     */
    public static disConnect (cb) {
        pomelo.disconnect(cb);
        pomelo.off("push", this.onPushMessageBindFunc);
    }
    // 请求
    public static request (cmd, data, callback) {
        pomelo.request(cmd, data, (data)=>{
            if (data.ret === 0) {
                if (data.data && data.data.model) {
                    Model.update(data.data.model);
                }
            } else {
                TipUi.instance.showTip(JSON.stringify(data));
            }
            callback(data.ret, data.data);
        });
    };

    private static onPushMessage(data:any) {
        console.log("onPushMessage", data);
        if (data.data && data.data.model) {
            Model.update(data.data.model);
        }
    }
}
